import json
import datetime
import jwt
import redis

from ronglian_sms_sdk import SmsSDK
from alipay import AliPay
from django.conf import settings

# 容连云
ACCID = "8aaf07087f77bf96017fe419867a392b"
AUTHTOKEN = "2d395ced59ab470c85d6a63222f8febb"
APPID = "8aaf07087f77bf96017fe41987703932"

# 读取app私钥
app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH, 'r').read()
# 读取支付宝公钥
alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH, 'r').read()


def redis_conn():
    r = redis.Redis(host='localhost',port=6379,db=0)
    return r


# 封装jwttoken
class MyJwt:

    def __init__(self):

        # 初始化秘钥
        self.password = 'shuang'

    # 生命周期token
    def encode_time(self, userinfo):
        payload = {
            # 当前时间点 + 时间周期
            "exp": int((datetime.datetime.now() + datetime.timedelta(seconds=60*60*24)).timestamp()),
            'data': userinfo
        }

        encoded_jwt = jwt.encode(payload, self.password, algorithm="HS256")

        return encoded_jwt

    # 生成token
    def encode(self,userinfo):

        encoded_jwt = jwt.encode(userinfo, self.password, algorithm='HS256')

        return encoded_jwt

    # 解密方法
    def decode(self,token):

        decoded_json = jwt.decode(token,self.password,algorithms=['HS256'])

        return decoded_json


# 短信验证码
def send_message(sms_code,mobile,expire=5):

    sms_sdk = SmsSDK(accId=ACCID,accToken=AUTHTOKEN,appId=APPID)

    tid = '1'
    datas = ('%s'%sms_code,'%s'%expire)

    res = sms_sdk.sendMessage(tid,mobile,datas=datas)

    res_json = json.loads(res)

    if res_json.get('statusCode') == '00000':
        return sms_code
    else:
        return None


class MyAlipay:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.alipay = AliPay(
            appid="2021000119635066",
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            app_notify_url=None,
            sign_type='RSA2',
            debug=True,
        )

    def get_pay_url(self, order_id, total_amount):
        order_string = self.alipay.api_alipay_trade_page_pay(
            subject="商家收款",
            out_trade_no=order_id,
            total_amount=total_amount,
            return_url="http://127.0.0.1:8000/user/order",
            notify_url="http://127.0.0.1:8000/user/order",
        )
        # 支付地址
        return "https://openapi.alipaydev.com/gateway.do?" + order_string

    def check(self, out_trade_no):
        try:
            # 主动查询支付结果
            pay_result = self.alipay.api_alipay_trade_query(out_trade_no)
            # 获取支付状态
            trade_staus = pay_result.get("trade_status")
            if trade_staus == "TRADE_SUCCESS":
                # 支付成功
                return True
                # 删除购物车已购买的商品
            else:
                # 支付失败
                return False
        except Exception as e:
            print("校验支付异常", e)
            return False


#  买家账号： fflpkl0295@sandbox.com
#  登陆密码： 111111
#  支付密码： 111111



